﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace UI_Test
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            LoadConfig();
            _dateEnd.SelectedDate = DateTime.Today;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var connectionString = _connectionString.Text;
            var email = _email.Text;
            var password = _password.Password;
            var dateStart = _dateStart.SelectedDate.Value;
            var dateEnd = _dateEnd.SelectedDate.Value;
            var companyKey = _companyKey.Text;
            var suppliers = _suppliers.Text.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var log = this.GetLog();

            var context = new EDEX_1C2CommerceML._1Cv81(connectionString);
            var document = context.GetCommerceML(
                context.GetJournalItems(
                context.GetJournal(dateStart, dateEnd)));

            if (suppliers.Any())
            {
                document.Items = document.Items
                    .Cast<CommerceML.Version205.Документ>()
                    .Where(r => r.Контрагенты.Any(n => suppliers.Contains(n.Ид)))
                    .ToArray();
            }

            if (log.Any())
            {
                document.Items = document.Items
                    .Cast<CommerceML.Version205.Документ>()
                    .Where(r => !log.Contains(r.Ид))
                    .ToArray();
            }

            this.AddToLog(document.Items
                .Cast<CommerceML.Version205.Документ>()
                .Select(r => r.Ид));

            using (var writeStream = new System.IO.StreamWriter(_path.Text))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommerceML.Version205.КоммерческаяИнформация));
                serializer.Serialize(writeStream, document);
                writeStream.Close();
            }

            using (var stream = new System.IO.FileStream(_path.Text, System.IO.FileMode.Open))
            {
                var edex = new EdexApiClient.EdexApiContext(email, password);
                edex.ChangeCompany(companyKey);
                edex.UploadOutgoingInvoices(stream, "CommerceML.xml");
                stream.Close();
            }
            SaveConfig();

            MessageBox.Show("Operation Completed");
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var connectionString = _connectionString.Text;
            var email = _email.Text;
            var password = _password.Password;
            var dateStart = _dateStart.SelectedDate.Value;
            var dateEnd = _dateEnd.SelectedDate.Value;
            var companyKey = _companyKey.Text;
            var path = _path.Text;
            var suppliers = _suppliers.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var log = this.GetLog();

            if (System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            var context = new EDEX_1C2CommerceML._1Cv81(connectionString);
            var document = context.GetCommerceML(
                context.GetJournalItems(
                context.GetJournal(dateStart, dateEnd)));

            if (suppliers.Any())
            {
                document.Items = document.Items
                    .Cast<CommerceML.Version205.Документ>()
                    .Where(r => r.Контрагенты.Any(n => suppliers.Contains(n.Ид)))
                    .ToArray();
            }

            if (log.Any())
            {
                document.Items = document.Items
                    .Cast<CommerceML.Version205.Документ>()
                    .Where(r => !log.Contains(r.Ид))
                    .ToArray();
            }

            this.AddToLog(document.Items
                .Cast<CommerceML.Version205.Документ>()
                .Select(r => r.Ид));

            using (var writeStream = new System.IO.StreamWriter(path))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommerceML.Version205.КоммерческаяИнформация));
                serializer.Serialize(writeStream, document);
            }
   
            SaveConfig();

            MessageBox.Show("Operation Completed");
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            var email = _email.Text;
            var password = _password.Password;
            var companyKey = _companyKey.Text;

            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".xml";
            dlg.Filter = "CommerceML documents (.xml)|*.xml";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                using (var stream = new System.IO.FileStream(filename, System.IO.FileMode.Open))
                {
                    var edex = new EdexApiClient.EdexApiContext(email, password);
                    edex.ChangeCompany(companyKey);
                    edex.UploadOutgoingInvoices(stream, "CommerceML.xml");
                }
                SaveConfig();

                MessageBox.Show("Operation Completed");

            }
        }

        private IEnumerable<string> GetLog()
        {
            if (!System.IO.File.Exists("log.xml"))
            {
                var document = new XDocument(
                    new XElement("logs"));

                document.Save("log.xml");
            }

            return XDocument.Load("log.xml")
                .Descendants("document")
                .Select(r => r.Attribute("id").Value);
        }

        private void AddToLog(IEnumerable<string> data)
        {
            var document = XDocument.Load("log.xml");
            document.Root.Add(
                new XElement("log",
                    new XAttribute("date", DateTime.Now.ToString()),
                    data.Select(r => new XElement("document", new XAttribute("id", r)))));

            document.Save("log.xml");
        }

        private void LoadConfig()
        {
            var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

            if (config.AppSettings.Settings.AllKeys.Contains("connectionString"))
                _connectionString.Text = System.Configuration.ConfigurationManager.AppSettings["connectionString"];
            else
                config.AppSettings.Settings.Add("connectionString", _connectionString.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("ApiUri"))
                _ApiUri.Text = System.Configuration.ConfigurationManager.AppSettings["ApiUri"];
            else
                config.AppSettings.Settings.Add("ApiUri", _ApiUri.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("RootUri"))
                _RootUri.Text = System.Configuration.ConfigurationManager.AppSettings["RootUri"];
            else
                config.AppSettings.Settings.Add("RootUri", _RootUri.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("email"))
                _email.Text = System.Configuration.ConfigurationManager.AppSettings["email"];
            else
                config.AppSettings.Settings.Add("email", _email.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("password"))
                _password.Password = System.Configuration.ConfigurationManager.AppSettings["password"];
            else
                config.AppSettings.Settings.Add("password", _password.Password);

            if (config.AppSettings.Settings.AllKeys.Contains("syncDate"))
                _dateStart.SelectedDate = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["syncDate"]);
            else
                config.AppSettings.Settings.Add("syncDate", DateTime.Today.ToString());

            if (config.AppSettings.Settings.AllKeys.Contains("companyKey"))
                _companyKey.Text = System.Configuration.ConfigurationManager.AppSettings["companyKey"];
            else
                config.AppSettings.Settings.Add("companyKey", _companyKey.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("suppliers"))
                _suppliers.Text = String.Join("\r\n", System.Configuration.ConfigurationManager.AppSettings["suppliers"].Split(','));
            else
                config.AppSettings.Settings.Add("suppliers", _suppliers.Text);

            if (config.AppSettings.Settings.AllKeys.Contains("path"))
                _path.Text = System.Configuration.ConfigurationManager.AppSettings["path"];
            else
                config.AppSettings.Settings.Add("path", _path.Text);

            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
        }

        private void SaveConfig()
        {
            var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

            config.AppSettings.Settings.Remove("connectionString");
            config.AppSettings.Settings.Remove("ApiUri");
            config.AppSettings.Settings.Remove("RootUri");
            config.AppSettings.Settings.Remove("email");
            config.AppSettings.Settings.Remove("password");
            config.AppSettings.Settings.Remove("syncDate");
            config.AppSettings.Settings.Remove("companyKey");
            config.AppSettings.Settings.Remove("suppliers");
            config.AppSettings.Settings.Remove("path");

            config.AppSettings.Settings.Add("connectionString", _connectionString.Text);
            config.AppSettings.Settings.Add("ApiUri", _ApiUri.Text);
            config.AppSettings.Settings.Add("RootUri", _RootUri.Text);
            config.AppSettings.Settings.Add("email", _email.Text);
            config.AppSettings.Settings.Add("password", _password.Password);
            config.AppSettings.Settings.Add("syncDate", _dateEnd.SelectedDate.ToString());
            config.AppSettings.Settings.Add("companyKey", _companyKey.Text);
            config.AppSettings.Settings.Add("suppliers", String.Join(",", _suppliers.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)));
            config.AppSettings.Settings.Add("path", _path.Text);   

            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
        }

    }
}
